/**
 * 
 */
package com.jiang.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

/**
 * @author Administrator
 * @文件上传工具类，与具体的业务无关
 */
public class FileUploadUtils {

	public static String createFileName(String mime) {

		String fileName = null;
		if (StringUtils.isNotBlank(mime)) {

			String typeName = "";

			switch (mime) {
			case "image/jpeg":
				typeName = "jpg";
				break;
			case "image/bmp":
				typeName = "bmp";
				break;
			case "image/gif":
				typeName = "gif";
				break;
			case "image/png":
				typeName = "png";
				break;
			}

			fileName = UUID.randomUUID().toString() + "." + typeName;
		}

		return fileName;
	}

	/**
	 * 
	 * @param file 源文件 @param filePath 文件上传路径 @return @throws
	 */
	public static boolean uploadFile(File file, String filePath) {

		boolean flag = false;

		if (file != null && StringUtils.isNotBlank(filePath)) {

			OutputStream out = null;
			InputStream is = null;

			try {
				is = new FileInputStream(file);
				File outFile = new File(filePath);
				out = new FileOutputStream(outFile);
				// 判断父目录是否存在
				if (!outFile.getParentFile().exists()) {
					outFile.getParentFile().mkdirs();
				}
				byte[] bytes = new byte[2048];
				int len = 0;
				while ((len = is.read(bytes)) != -1) {
					out.write(bytes, 0, len);
				}
				out.flush(); // 全部刷出去
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (out != null) {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return flag;
	}
}
